<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019-07-03
  Time: 16:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>发货计划</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
    <style type="text/css">
        .layui-table-click{
            background-color:#ddf2e9 !important;
        }
    </style>
</head>
<!-- 添加框中详情填写时上下左右切换 -->
<script type="text/javascript">
	$(document).on('keydown','[lay-id="productAddTable"] .layui-table-edit',function(e){
		var td = $(this).parent('td'),
		tr = td.parent('tr'),
		trs = tr.parent().parent().find('tr'),
		tr_index = tr.index(),
		td_index = td.index(),
		td_last_index = tr.find('[data-edit="text"]:last').index(),
		td_first_index = tr.find('[data-edit="text"]:first').index();
		switch(e.keyCode){
			case 13:
			case 39:
				td.nextAll('[data-edit="text"]:first').click();
				if(td_index == td_last_index){
					tr.next().find('td').eq(td_first_index).click();
					if(tr_index == trs.length-1){
						trs.eq(0).find('td').eq(td_first_index).click();
					}
				}
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 37:
				td.prevAll('[data-edit="text"]:first').click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 38:
				tr.prev().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 40:
				tr.next().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
		} 
	})
</script>
<body>
	<div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="">首页</a>
            <a>
              <cite>发货计划</cite>
            </a>
        </span>
    </div>
    <!-- 主体内容 -->
    <div class="x-body">
	    <!-- 顶部搜索框 -->
        <div style="margin-bottom: 18px">
            <div class="layui-inline">
                <table>
                    <tr>
                        <td>
                            <div class="layui-form" style="width: 180px; margin-left: 10px">
                                <input class="layui-input" id="keyword01" placeholder="请输入生产计划单号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
                            </div>
                        </td>
                        <td>
                            <div class="layui-form" style="width: 180px; margin-left: 10px">
                                <input class="layui-input" id="keyword02" placeholder="请输入供应商名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
                            </div>
                        </td>
                        <td>
                            <div class="layui-form" style="width: 180px; margin-left: 10px">
                                <input class="layui-input" id="keyword03" placeholder="请输入仓库名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <button class="layui-btn layui-btn-normal" data-type="reload" style="margin-left: 25px;"><i class="layui-icon layui-icon-search"></i>检索</button>
        </div>
         <!-- 头部按钮 -->
        <xblock>
            <button id="add" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-add-circle-fine"></i>创建发货计划</button>
            <button id="deletes" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
        </xblock>
        <!-- 发货计划列表 -->
        <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
        <br/><br/>
        <div id="detailsDiv">
	        <xblock>
				<button class="layui-btn layui-btn-warm" id="addProduct2"><i class="layui-icon layui-icon-add-circle-fine"></i>新增物料</button>
				<button class="layui-btn layui-btn-danger" id="delete2"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
			</xblock>
	        <!-- 发货计划详情列表 -->
	        <table class="layui-hide" id="tableDetailList" lay-filter="tableDetailList"></table>
        </div>
        
    </div>
   	<!-- 行编辑 -->
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
	</script>
	
	<!-- 发货计划新增框 -->
	<div id="addDivID" hidden="hidden">
		<form class="layui-form" id="addFormID">
			<xblock>
				<table>
					<tr>
						<td>
							<label class="layui-form-label">仓库名称</label>
							<!-- 主表id 编辑时有值 ，用于判断是进行新增操作或编辑操作 -->
							<input id="id" name="id" type="hidden">
						</td>
						<td>
							<div class="layui-input-inline" style="width:160px">
								<select class="layui-input" name="warehouse_id" id="warehouse_id" lay-filter="sendCompany">
									<option value="">请选择仓库</option>
									<c:forEach items="${allWarehouse}" var="warehouse" >
										<option value="${warehouse.id}">${warehouse.warehouse_name}</option>
									</c:forEach>
								</select>
							</div>
							<div class="layui-inline" style="margin-top: 10px;">
								<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
							</div>
						</td>
						<td>
							<label class="layui-form-label">供应商</label></td>
						<td>
							<div class="layui-input-inline" style="width:160px">
								<select class="layui-input" name="supplier_id" id="supplier_id" lay-filter="sendCompany">
									<option value="">请选择供应商</option>
									<c:forEach items="${customer_type0}" var="customer" >
										<option value="${customer.id}">${customer.customer_name}</option>
									</c:forEach>
								</select>
							</div>
							<div class="layui-inline" style="margin-top: 10px;">
								<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
							</div>
						</td>
						<td>
	                        <button type="button" class="layui-btn layui-btn-normal" id="addProduct">选择物料</button>
	                    </td>
					</tr>
					<tr style="height:10px"></tr>
				</table>
			</xblock>
			<!-- 详情添加表 -->
			<table id="productAddTable" lay-filter="productAddTable"></table>
			<xblock>
				<div align="center">
					<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm">提交</button>
					&emsp;&emsp;&emsp;&emsp;
					<button class="layui-btn layui-btn-primary">取消</button>
				</div>
			</xblock>
		</form>
	</div>
	
	<!-- 发货计划新增框使用的产品选择框 -->
	<div id="productDiv" hidden="hidden">
		<form class="layui-form">
			<div style="margin-bottom: 18px">
				<div class="layui-inline">
					<table style="margin-top: 10px">
						<tr>
							<td>
								<input class="layui-input" id="materiel_num" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
							</td>
						</tr>
					</table>
				</div>
				&emsp;
				<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" data-type="reloadm1"><i class="layui-icon layui-icon-search"></i>检索</button>
			</div>
			<table id="productTable" lay-filter="productTable"></table>
			<input id="dtim" type="hidden">
			<xblock>
				<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>
			</xblock>
		</form>
	</div>
	<!-- 直接添加详情使用产品选择框 -->
	<div id="productDiv2" hidden="hidden">
		<form class="layui-form" id="addFormID2">
			<div style="margin-bottom: 18px">
				<div class="layui-inline">
					<table style="margin-top: 10px">
						<tr>
							<td>
								<input class="layui-input" id="materiel_num2" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
							</td>
						</tr>
					</table>
				</div>
				&emsp;
				<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" data-type="reloadm2"><i class="layui-icon layui-icon-search"></i>检索</button>
			</div>
			<table id="productTable2" lay-filter="productTable2"></table>
			<xblock>
				<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform2" type="button" style="margin: 0px 0px 10px 500px; width: 400px;margin-left: 250px;">提交</button>
			</xblock>
		</form>
	</div>
	
	<!-- 实现功能 -->
	<script type="text/javascript">
		var table;
	    var planId;
	    //主表行点击事件是主表当前行状态
	    var status;
	    layui.use(['table','layer','form','upload'], function() {
            //layui 准备工作
	    	table = layui.table;
            var layer = layui.layer;
            var form = layui.form;
            var upload = layui.upload;

			//检索事件
			var $ = layui.jquery, active = {
				//主表检索
				reload : function() {
					var keyword01 = $.trim($("#keyword01").val());
					var keyword02 = $.trim($("#keyword02").val());
					var keyword03 = $.trim($("#keyword03").val());
					table.reload('storageAreaTableId', {
						method : 'get',
						where : {
							"plan_number" : keyword01,
							"supplier_name" : keyword02,
							"warehouse_name" : keyword03
						},
						//重新从第一页开始
						page : {
							curr : 1
						}
					});
				},

				//新增框物料检索
				reloadm1 : function() {
					var materiel_num = $.trim($('#materiel_num').val());
					var split = materiel_num.split(',')
					if (split.length <= 5) {
						table.reload('productTable', {
							method : 'get',
							where : {
								"materielNum" : materiel_num
							}
						});
					} else {
						layer.msg("最多可同时查5个！");
					}
				},
				//详情选择物料框检索物料
				reloadm2 : function() {
					var materiel_num = $.trim($('#materiel_num2').val());
					var split = materiel_num.split(',')
					if (split.length <= 5) {
						table.reload('andProcut2Id', {
							method : 'get',
							where : {
								"materielNum" : materiel_num
							}
						});
					} else {
						layer.msg("最多可同时查5个！");
					}
				}
			}
			/*************************************** 加载时初始设置  star******************************************/
			 //加载时隐藏详情div
         	$("#detailsDiv").hide();
			/*************************************** 加载时初始设置 end******************************************/
			/**************************************** 表格整体设置 star*******************************************/
			//点击行checkbox选中
    	    $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
    	        var index = $(this).attr('data-index');
    	        var tableBox = $(this).parents('.layui-table-box');
    	        //存在固定列
    	        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
    	            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
    	        } else {
    	            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
    	        }
    	        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
    	        if (checkCell.length>0) {
    	            checkCell.click();
    	        }
    	    });
    	    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
    	        e.stopPropagation();
    	    });
            $('.layui-btn').on('click', function () {
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });
			/**************************************** 表格整体设置 end*******************************************/

          	//监听复选框事件，被选中的行高亮显示
    	    table.on('checkbox(tableList)', function(obj){
    	    	if(obj.checked == true && obj.type == 'all'){
    		        //点击全选
    		        $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
    		    }else if(obj.checked == false && obj.type == 'all'){
    		        //点击全不选
    		        $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
    		    }else if(obj.checked == true && obj.type == 'one'){
    		        //点击单行
    			    if(obj.checked == true){
    			          obj.tr.addClass('layui-table-click');
    			    }else{
    			          obj.tr.removeClass('layui-table-click');
    			    }
    		    }else if(obj.checked == false && obj.type == 'one'){
    		        //点击全选之后点击单行
    		        if(obj.tr.hasClass('layui-table-click')){
    		        	obj.tr.removeClass('layui-table-click');
    		        }
    		    }
    	    });
			
    	    /* 生产计划列表 */
            table.render({
                elem: '#tableList'
                ,url:'${pageContext.request.contextPath }/DispatchBill/list.do'
                ,title: '发货计划列表'
                ,id :'storageAreaTableId'
                ,limits:[10,20,30]
                ,cols: [[
					{type: 'checkbox',fixed: 'left'},
                    {field:'', title:'序号', type:'numbers', align:'center'},
                    {field:'supplier_name', title:'供应商名称', align:'center'},
                    {field:'warehouse_name', title:'仓库名称', align:'center'},
                    {field:'client_name', title:'主机厂名称', align:'center'},
                    {field:'plan_number', title:'生产计划单号', align:'center'},
                    {field:'user_name', title:'创建人', align:'center'},
                    {field:'create_date', title:'创建日期', align:'center'},
                    {field:'status', title:'计划单状态', align:'center',templet: function(d){
          	    		if (d.status == 0) {
        	    			return '新纪录';
        				}else if(d.status == 1){
        					return '已处理';
        				}
                    }}
                    ,{field:'remark', title:'备注', align:'center', edit: true, event:'remark'}
                    /* ,{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar',width:100, align: 'center'}  */
                ]]
                ,page: true
                ,done : function(){
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
            });
          	//"补货计划"的行内编辑事件
            table.on('edit(tableList)', function(obj){
                var fieldValue = obj.value, 	//得到修改后的值
                    rowData = obj.data, 		//得到所在行所有键值
                    fieldName = obj.field; 		//得到字段
                	//console.log(rowData.mNum);
                $.ajax({
                    type: "post",
                    url: "${pageContext.request.contextPath }/DispatchBill/update.do",
                    data: { id:rowData.id, remark:fieldValue },
                    success: function(data){
                        if(data > 0){
                        	toastr.success("修改成功！");
                        }else{
                        	toastr.error("修改失败！");
                        }
                    }
                });
            });
          	//"补货计划"的监听行工具事件
			table.on('tool(tableList)', function(obj){
				var data = obj.data;
				if(obj.event === 'edit'){
					layer.open({
	                    type: 1 					//Page层类型
	                    ,area: ['1100px', ''] 		//宽  高
	                    ,title: '编辑'
	                    ,shade: 0.6 				//遮罩透明度
	                    ,maxmin: true 				//允许全屏最小化
	                    ,anim: 1 					//0-6的动画形式，-1不开启
	                    ,content: $('#addDivID')
	                    ,end: function () {
	                        var formDiv = document.getElementById('addDivID');
	                        formDiv.style.display = '';
	                    }
	                    ,success: function(){
	                    	table.reload('productAddTable',{
	                            data : new Array()
	                        });
	                    	$("#id").val(data.id)
	                        form.render();
	                    }
	                });
				}
			});
          	
          	
			//监听行单击事件(子表：生产计划详情)
	       	table.on('row(tableList)', function(obj){
	       		//显示详情div
	            $("#detailsDiv").show()
	            //给主表行点击事件是主表当前行状态赋值
	       		status = obj.data.status;
	       	  	table.render({
	       		    elem: '#tableDetailList'
	       		    ,url:'${pageContext.request.contextPath }/DispatchBillDetail/list.do'
	       		    ,where:{dispatchId: obj.data.id}
	       		    ,title: '产品的配件详情数据表'
	       		    ,id :'contentDetialTable'
	       		    ,limits:[10,20,30]
	       		    ,cols: [[
						{type: 'checkbox',fixed: 'left'},
	       		    	{field:'left', title:'序号', sort: true, type:'numbers', width: 60},
	       		    	{field:'materiel_name', title:'物料名称', align:'center'},
	       		    	{field:'materiel_num', title:'SAP/QAD', align:'center'},
	                    {field:'planQuantity', title:'生产计划数量', align:'center'},
	                    {field:'storageQuantity', title:'线边库存数量', align:'center'},
	                    {field:'astock', title:'安全库存数量', align:'center'},
	                    {field:'shipmentsQuantity', title:'需发货数量', edit: true, align:'center'},
	                    {field:'remark', title:'备注', align:'center', edit: true, event:'remark'}
	       		    ]]
	       		    ,page: true
		       		 ,done : function(){
	                    $('th').css({
	                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                    })
	                }
	       		});
	       	});
	      	//"补货计划详情"的行内编辑事件
            table.on('edit(tableDetailList)', function(obj){
                var fieldValue = obj.value, 	//得到修改后的值
                    rowData = obj.data, 		//得到所在行所有键值
                    fieldName = obj.field; 		//得到字段
                	//console.log(rowData.mNum);
                var data = { id:rowData.id, remark:fieldValue };
                if(status != 0){
					toastr.warning("该单据已处理不能修改！");
					return ;
				}
                if(fieldName == "shipmentsQuantity"){
                	var patrn = /^[0-9]*$/;
                   	if(!patrn.test(fieldValue)){
                   		toastr.warning("只能是数字！");
                   		setTimeout(function(){
                            //window.location.reload();
                            table.reload('contentDetialTable',{
                                method:'get',
            	                page: {
            	                    curr: 1//重新从第 1 页开始
            	                }
                            });
                        },1000);
                   		return;
                   	}else{
	                	data = { id:rowData.id, shipmentsQuantity:fieldValue };
                   	}
                }
                $.ajax({
                    type: "post",
                    url: "${pageContext.request.contextPath }/DispatchBillDetail/update.do",
                    data: data,
                    success: function(data){
                        if(data > 0){
                        	toastr.success("修改成功！");
                        }else{
                        	toastr.error("修改失败！");
                        	setTimeout(function(){
                                //window.location.reload();
                                table.reload('contentDetialTable',{
                                    method:'get',
                	                page: {
                	                    curr: 1//重新从第 1 页开始
                	                }
                                });
                            },1000);
                        }
                    }
                });
            });
	      	
	      	//新增框中详情添加表
            table.render({
                elem: '#productAddTable'
                ,defaultToolbar:['filter', 'print']
                ,cols: [[
                    {type: 'checkbox',fixed: 'left'},
                    {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                    {field:'id', title:'id', align:'center', hide:true},
                    {field:'mid', title:'mid', align:'center', hide:true},
                    {field:'customer_name', title:'供应商名称', align:'center',width:100},
                    {field:'materiel_num', title:'SAP/QAD', align:'center'},
                    {field:'materiel_name', title:'中文名称', align:'center', width:150},
                    {field:'packing_quantity', title:'包装数量', align:'center', width: 90},
                    {field:'shipments_quantity', title:'<span style="color: red">需发货数量</span>', edit: 'text', align:'center', width: 110},
                ]]
                ,limit:Number.MAX_VALUE
                ,page: false
                ,height: 400
                ,done : function(){
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
            });
	      	
          //增加
            $("#add").click(function(){
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['1100px', ''] 		//宽  高
                    ,title: '新增'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,end: function () {
                        var formDiv = document.getElementById('addDivID');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                    	table.reload('productAddTable',{
                            data : new Array()
                        });
                        form.render();
                    }
                });
			});
            /**
             * 新增--提交
             */
            form.on('submit(addForm)', function (data) {
                var receiveNumber = $("#receiveNumber").val();
                //获取明细中数据
                var oldData = table.cache["productAddTable"];
                var data = oldData.filter(function(item){
                    var re = /^[0-9]\d*$/ ;
                    return !re.test(item.shipments_quantity) || item.shipments_quantity == "" ||  item.shipments_quantity == null;
                })
                if(oldData.length == 0){
                    toastrStyle();
                    toastr.warning("请添加物料详情！");
                    return false;
                } else if (data.length > 0){
                    toastrStyle();
                    toastr.warning("请输入正确的需发货数量(大于0的正整数)");
                	return false;
                } else {
                	var materiel_ids = new Array();
                    var shipments_quantitys = new Array();
                    for (var i = 0; i < oldData.length; i++) {
                    	materiel_ids.push(oldData[i].id);
                    	shipments_quantitys.push(oldData[i].shipments_quantity);
					}
                    var title = "新增";
                    var url = '${pageContext.request.contextPath}/DispatchBill/pLinsert.do';
                    var id = $.trim($("#id").val());
                    if(id != "" && id != null && id != 'undefined'){
                        var url = '${pageContext.request.contextPath}/DispatchBill/pLupdate.do';
                        title = "修改";
                    }
                    //添加收货单
                    $.ajax({
                        url : url,
                        data: $("#addFormID").serialize()+"&materiel_ids="+materiel_ids+"&shipments_quantitys="+shipments_quantitys,
                        cache : false,
                        async: false,
                        type : "post",
                        success:function(res){
                            if (res > 0) {
                            	toastr.success(title+'成功');
                            	setTimeout(function(){
                                	layer.closeAll();
                                	table.reload('storageAreaTableId',{
               	                      	method:'get',
               	                       	page: {
               	                      		//重新从第 1 页开始
               	                          	curr: 1
               	                     	}
                                	});
                                },1000);
                            }else{
                            	toastr.error(title+'失败！');
                                setTimeout(function(){
                                	layer.closeAll();
                                },1000);
                            } 
                        }
                    })
                    return false;
                }
            });
          	
          	//批量删除
            $('#deletes').click(function(obj){
                var rowData = table.checkStatus('storageAreaTableId');
                var data = rowData.data;
                var str = "";
                var sum = 0;
                if(data.length==0){
                    toastr.warning("请至少选择一条记录！");
                }else{
                    for(var i=0;i<data.length;i++){
                        str += data[i].id;
                        if(i != data.length-1){
                            str += ",";
                        }
                        if(data[i].status == 0){
                        	sum += 1;
                        }
                    }
                    if(sum == data.length){
                    	layer.confirm('确定删除吗？', function(index){
                            $.ajax({
                                type:'post',
                                url:'${pageContext.request.contextPath }/DispatchBill/delete.do',
                                data:{"ids":str},
                                dataType : "json",
                                success:function(data){
                                    if(data>0){
                                        toastr.success("删除成功！");
                                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                            //关闭模态框
                                            // 父页面刷新
                                        	layer.closeAll();
                                        	table.reload('storageAreaTableId',{
                       	                      	method:'get',
                       	                       	page: {
                       	                      		//重新从第 1 页开始
                       	                          	curr: 1
                       	                     	}
                                        	});
                                        },1000);
                                    }else{
                                        toastr.error("删除失败！");
                                    }
                                }
                            })
                            layer.close(index);
                        });
                    }else{
                    	toastr.warning("已处理的数据不能删除！");
                    }
                }
            });

            /*================点击选择物料的弹框================*/
            $("#addProduct").click(function() {
                if ($("#supplier_id").val() == "" || $("#supplier_id").val() == null || $("#warehouse_id").val() == "" || $("#warehouse_id").val() == null) {
                    //toastr.warning("请选择供应商！");
                    layer.msg("请选择完整仓库和供应商！");
        		} else {
                    productIndex = layer.open({
                        type: 1 					//Page层类型
                        ,area: ['900px', '700px'] 	//宽  高
                        ,title: '物料清单'
                        ,shade: 0.6 				//遮罩透明度
                        ,maxmin: true 				//允许全屏最小化
                        ,anim: 1 					//0-6的动画形式，-1不开启
                        ,content: $('#productDiv')
                        ,end: function () {
                            var formDiv = document.getElementById('productDiv');
                            formDiv.style.display = '';
                        }
                        ,success: function () {
                            var customer_id = $("#supplier_id").val();
                            table.render({
                                elem: '#productTable'
                               	,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?customer_id='+customer_id
            	                ,limits:[10,20,30]
                                /* ,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageMaterielByCustomerIdAndWarehouseId.do?customerId='+customer_id+'&source=1'
                                ,limit: 10000// 数据表格默认全部显示 */
                                ,defaultToolbar:['filter', 'print']
                                ,cols: [
                                    [{
                                        type: 'checkbox',
                                        fixed: 'left'
                                    }, {
                                        field:'id',
                                        title:'序号',
                                        sort: true,
                                        width: 60,
                                        type:'numbers',
                                        align:'center'
                                    }, {
                                        field: 'id',
                                        title: 'id',
                                        hide:true
                                    } , {
                                        field: 'materiel_num',
                                        title: 'SAP/QAD',
                                        align:'center',
                                	}, {
                                        field: 'materiel_name',
                                        title: '中文名称',
                                        align:'center',
                                    }, {
                                        field: 'packing_quantity',
                                        title: '包装数量',
                                        align:'center',
                                    }
                                    ]
                                ]
                                ,page: false
                            });
                          	/* **********键盘Enter事件*********** */
                            $(document).keydown(function (event) {
                                if (event.keyCode == 13) { //绑定回车 
                             		var materiel_num=$('#materiel_num').val();
                             		var table = layui.table;
                             		var verify = /^[0-9,-]*$/;
                            		//if(verify.test(materiel_num)){
                            			var split = materiel_num.split(',')
                            			if(split.length <= 5){
                            				table.reload('productTable',{ 
                        						method:'post'
                        						,where:{"materielName":materiel_name,"materielNum":materiel_num}
                        					});
                            			}else{
                            				layer.msg("最多可同时查5个！");
                            			}
                                	return false;
                                };
                            });
                          	/* **********Enter事件*********** */
                          	
                        }
                    });
        		}
            });
            
            //添加弹框中，选择物料后，点提交，带回的操作
            form.on('submit(productform)', function (data) {
                var flag;
                var oldData = table.cache["productAddTable"];
                var checkStatus = table.checkStatus('productTable')
                //选中的物料
                var data = checkStatus.data;
                for (var j = 0; j < data.length; j++) {
                    for (var k = 0; k < oldData.length; k++) {
                        if (oldData[k].id == data[j].id) {
                            flag = 0;
                        }
                    }
                }
                if (flag != 0) {
                    for (var i = 0; i < data.length; i++) {
                        oldData.push(data[i]);
                    }
                } else {
                    toastr.warning("记录已经存在，不能重复添加");
                }
                table.reload('productAddTable',{
                    data : oldData
                });
                $('[lay-id="productAddTable"] [data-edit="text"]:first').click();
                layer.close(productIndex)
                return false;
            });
            
          //llm 收货单详情添加物料
            $("#addProduct2").click(function() {
           
            	var checkStatus = table.checkStatus('storageAreaTableId')
                var data = checkStatus.data;
            	var str = "";
            	if(data.length == 0){
                    toastr.warning("请选择一条记录！");
                } else if(data.length > 1){
                	toastr.warning("只能选择一条记录！");
                }else if(data[0].status!= "0"){
               		toastr.warning("对不起，已处理的数据不能添加物料！");
                }else{
                	var customerId2 = data[0].supplier_id;
                	layer.open({
                		type: 1 					//Page层类型
                        //,area: ['900px', '700px'] 	//宽  高
                        ,area: ['900px', ''] 	//宽  高
                        ,title: '物料清单'
                        ,shade: 0.6 				//遮罩透明度
                        ,maxmin: true 				//允许全屏最小化
                        ,anim: 1 					//0-6的动画形式，-1不开启
                        ,content: $('#productDiv2')
                        ,end: function () {
                            var formDiv = document.getElementById('productDiv2');
                            formDiv.style.display = '';
                            $("#materiel_num2").val("")
                        }
                        ,success: function(){
                        	table.render({
                                elem: '#productTable2'
                                ,id:'andProcut2Id'
                               	,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?customer_id='+customerId2
           	                    ,limits:[10,20,30]
                                /* ,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageMaterielByCustomerIdAndWarehouseId.do?customerId='+customerId2+'&source=1'
                                ,limit:10000 */
                                ,defaultToolbar:['filter', 'print']
                                
                                ,cols: [
                                    [{
                                        type: 'checkbox',
                                        fixed: 'left'
                                    }, {
                                        field:'id2',
                                        title:'序号',
                                        sort: true,
                                        width: 60,
                                        type:'numbers',
                                        align:'center'
                                    }, {
                                        field: 'id',
                                        title: 'id',
                                        hide: true
                                    } , {
                                        field: 'materiel_num',
                                        title: 'SAP/QAD',
                                        align:'center',
                                    /* }, {
        	                            field: 'brevity_num',
        	                            title: '零件号',
        	                            align:'center', */
                                	}, {
                                        field: 'materiel_name',
                                        title: '中文名称',
                                        align:'center',
                                    }, {
                                        field: 'packing_quantity',
                                        title: '包装数量',
                                        align:'center',
                                    }, {
                                        field: 'shipments_quantity',
                                        title: '需发货数量',
                                        align:'center',
                                        edit:true,
                                  }
                                ]]
                                ,page: false
                            });
                        	
                        
                        }
                	});
                }
           
            });
            /**
             * 下表添加物料提交
             */
            form.on('submit(productform2)', function (data) {
            	//获取该表格中选中的数据
            	var checkStatus = table.checkStatus('andProcut2Id')
            	var checkData = checkStatus.data;
            	//获取明细中数据
                //var oldData = table.cache["andProcut2Id"];
            	//alert(checkData.length);
                var data = checkData.filter(function(item){
                    var re = /^[0-9]\d*$/ ;
                    return !re.test(item.shipments_quantity) || item.shipments_quantity == "" ||  item.shipments_quantity == null;
                })
                if(checkData.length == 0){
                    toastrStyle();
                    toastr.warning("请添加物料详情！");
                    return false;
                } else if (data.length > 0){
                    toastrStyle();
                    toastr.warning("请输入正确的需发货数量(大于0的正整数)");
                	return false;
                }  else {
                	var zhuBiao = table.checkStatus('storageAreaTableId')
                    var zhuBiaoData = zhuBiao.data;
                	var dispatchId = zhuBiaoData[0].id;
    	        	for (var i = 0; i < checkData.length; i++) {
    	        		//checkData[i].id指的是物料id
    					var materiel_id = checkData[i].id;
    					var shipments_quantity = checkData[i].shipments_quantity;
    		            //添加收货明细
    		            $.ajax({
    		                url: '${pageContext.request.contextPath}/DispatchBillDetail/insert.do' ,
    		                type: 'post',
    		                data: {dispatchId:dispatchId,materielId:materiel_id, shipmentsQuantity:shipments_quantity},
    		                async: false,
    		                dataType:'JSON',
    		                success: function (result) {
    		                    if (result > 0) {
    		                    	toastr.success("新增成功！");
    		                    	setTimeout(function(){
    		                    		layer.closeAll();
    		                    		table.reload('contentDetialTable',{
                   	                      method:'get',
                   	                      page: {
                   	                      	//重新从第 1 页开始
                   	                          curr: 1
                   	                     }
                   	                  });
    		                    	},1000);
    		                    } else if (result == 0) {
    		                    	toastr.warning("该物料已存在，请选择其他物料");
    		                    	/* setTimeout(function(){
    	                                window.location.reload();
    	                            },1000); */
    		                    } else {
    		                        toastr.warning("对不起，明细添加失败！");
    		                    }
    		                },
    		                error: function (data) {
    		                	toastr.warning("对不起，请添加明细！");
    		                }
    		            })
    				}
                }
            });
          	//收货计划单详细批量删除
            $("#delete2").click(function() {
               	if(status != 0){
       		        toastr.warning("对不起，已处理的数据不能删除！");
   					return ;
   				}
            	var checkStatusParent = table.checkStatus('storageAreaTableId')
                var dataParent = checkStatusParent.data;
                var checkStatus = table.checkStatus('contentDetialTable')
                var data = checkStatus.data;
                var idArr = new Array();
                if(data.length == 0){
                    toastr.warning("请至少选择一条记录！");
                }else {
                    var ids = "";
                    for(var i = 0; i < data.length; i++) {
                        if(data[i].codeNum > 0){
                        	toastr.warning("对不起，已收货的数据不能删除！");
                            return;
                        }
                        if(i == 0 || i == "0"){
                            ids += data[i].id
                        } else {
                            ids += "," + data[i].id;
                        }
                    }
                    layer.confirm('确定删除吗？', function(index){
                        $.ajax({
                            type : 'post',
                            url : '${pageContext.request.contextPath }/DispatchBillDetail/delete.do',
                            data : {"ids":ids},
                            success : function(data){
                                if(data > 0) {
                                    toastr.success("删除成功！");
                                    setTimeout(function(){
                                    	 table.reload('contentDetialTable',{
                      	                      method:'get',
                     	                     	page: {
                      	                      	//重新从第 1 页开始
                      	                          curr: 1
                      	                      }
                      	                  });
                                    },1000);
                                } else {
                                    toastr.warning("删除失败！");
                                }
                            }

                        })
                        layer.closeAll();
                    });
                }
           
            });
            
		});
        /*提示框样式*/
        toastrStyle()
            
	</script>
</body>